﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Engine.Dtd.Schema;
using Engine.Sgml.Configuration;
using Engine.Sgml.Matching;

namespace Engine.Sgml.Validation.Rules {
    class RootRule : DefaultRule {
        public RootRule(SName name, ValidatorBehavior settings)
            : base(name, settings) {
            }

        public override bool Ignore(SElement element, SElement ancestor) {
            Guard.ArgumentNotNull(element, "element");
            if (ancestor == null)
                return false;
            if (ancestor.NodeType == SgmlNodeType.Document)
                return ContainsBefore(element.OrderIndex, element, ancestor.FirstNonInclusionNode());
            else if (element.NodeType == SgmlNodeType.EndElement && ancestor.Depth == 1)
                return false;
            else
                return true;
            }

        private static bool ContainsBefore(int position, SElement element, SElement item) {
            while (item != null && position > item.OrderIndex) {
                if (item.NodeType != SgmlNodeType.DocumentType && ElementMatcher.Match(item, element))
                    return true;
                item = item.NextNonInclusionNode();
                }
            return false;
            }

        }
    }
